package com.luo.d3s.ext.test.mock;

import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.lang.Nullable;
import redis.embedded.RedisServer;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.IOException;
import java.util.Optional;

/**
 * Redis Server（singleton服务端）Mock配置
 * <ul>
 *     <li>在本地启动RedisServer Mock实例</li>
 *     <li>可在单元测试类上通过注解导入配置：@Import({RedisServerMockConfiguration.class})</li>
 * </ul>
 *
 * @author luohq
 * @date 2023-01-09 14:16
 * @see <a href="https://github.com/codemonstur/embedded-redis">https://github.com/codemonstur/embedded-redis</a>
 */
public class RedisServerMockConfiguration {
    /**
     * 默认启动端口
     */
    private static final Integer DEFAULT_PORT = 6379;

    /**
     * RedisServer Mock实例
     */
    private RedisServer redisServer;

    public RedisServerMockConfiguration(@Nullable RedisProperties redisProperties) throws IOException {
        this.redisServer = new RedisServer(Optional.ofNullable(redisProperties).map(RedisProperties::getPort).orElse(DEFAULT_PORT));
    }

    @PostConstruct
    void postConstruct() throws IOException {
        redisServer.start();
    }

    @PreDestroy
    void preDestroy() throws IOException {
        redisServer.stop();
    }
}